package com.chb.demo.service;

import com.chb.demo.dao.AdminDao;
import com.chb.demo.entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminService {
    @Autowired
    AdminDao adminDao;

    public Page<Admin> findAllAdmin(int pageNo,int pageSize){
        PageRequest pageRequest = PageRequest.of((pageNo - 1) * pageSize, pageSize);
        System.out.println(pageRequest.toString());
        return  adminDao.findAll(pageRequest);

    }

    public String saveAdmin(String account,String password,
            String displayname, String id, String phone){
        try {
            adminDao.save(new Admin().setAccount(account)
                    .setPassword(password)
                    .setDisplayname(displayname)
                    .setId(id)
                    .setPhone(phone));
        }catch (Exception e){
            return "用户名重复";
        }

        return "插入成功";

    }

    public boolean bathDelete(List<String> accounts) {
        boolean success;
        try {
            for (String account: accounts ) {
                adminDao.delete(new Admin().setAccount(account));
            }
            success = true;
        }
        catch (Exception e){
            success = false;
        }
        return success;

    }

    public boolean oneDelete(String account) {
        boolean success;
        try {
            adminDao.delete(new Admin().setAccount(account));
            success = true;
        }
        catch (Exception e){
            success = false;
        }
        return success;
    }

    public boolean updateAdmin(String account, String password, String displayname, String id, String phone) {
        boolean success;
        try{
            adminDao.delete(new Admin().setAccount(account));
            adminDao.save(new Admin().setAccount(account)
                    .setPassword(password)
                    .setDisplayname(displayname)
                    .setId(id)
                    .setPhone(phone));
            success = true;
        }
        catch (Exception e){
            success = false;
        }
        return success;

    }
}
